//
//  CCYOauthController.swift
//  03.微博
//
//  Created by 蔡承毅 on 16/9/19.
//  Copyright © 2016年 IOS. All rights reserved.
//

import UIKit
import SVProgressHUD

class CCYOauthController: UIViewController {

    override func loadView() {
        self.view = webView
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = CCYDefaultBackgroundColor
        
        setupNavigationBar()
        
        // 使用WebView去加载网页(登录界面)
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        print("urlString=\(urlString)")
        let url = URL(string: urlString)!
        let urlRequest = URLRequest(url: url)
        webView.loadRequest(urlRequest)
        
        // 提示用户
        SVProgressHUD.show(withStatus: "正在加载登录页面...")
        
    }
    
    private func setupNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(autoFill))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(close))
    }
    
    func autoFill() -> Void {
        print("autoFill")
        let jsCode = "document.getElementById('userId').value = 'appleccy@126.com';document.getElementById('passwd').value = 'sina36808533'"
        // 让webView 实行js代码
        webView.stringByEvaluatingJavaScript(from: jsCode)
        
    }
    
    func close() -> Void {
        SVProgressHUD.dismiss()
        self.dismiss(animated: true, completion: nil)
    }
    
    // MARK: - 懒加载
    lazy var webView: UIWebView = UIWebView()

}

//extension CCYOauthController: UIWebViewDelegate{
//    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        let urlString = request.url?.absoluteURL
//        
//        print("request = \(urlString)")
//        
//        return true
//    }
//}
extension CCYOauthController: UIWebViewDelegate{
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.url!.absoluteString
        print("urlString \(urlString)")
        
        // 点击取消 urlString http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        
        // 点击确定 urlString http://www.baidu.com/?code=dce804682e577ee5648c01cf98a4ab05
        
        if !urlString.hasPrefix(redirect_uri) {
            // 不是授权回调开头，让它加载
            return true
        } else {
            print("是回调开头")
            let query = request.url?.query
            print("query:n\(query)")
            let codeString = "code="
            if query!.hasPrefix(codeString) {
                let nsQuery = query! as NSString
                
                let code = nsQuery.substring(from: codeString.characters.count)
                print("截取到的code:\(code)")
                
//                 loadAccessToken(code: code)
                CCYUserAccountVM.shared.loadAccessToken(code: code, completion: { (error) in
                    if error != nil{
                        print("加载accessToken出错:\(error)")
                        SVProgressHUD.show(withStatus: "您的网络不给力")
                        
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                            // 关闭浏览器
                            self.close()
                        })
                        return
                    }
                    print("加载accessToken成功")
                    self.close()
                    
                    UIApplication.shared.keyWindow?.rootViewController = CCYWelcomeViewController()
                })
            }else{
                // 取消，直接关闭控制器
                close()
            }
            
            return false
        }
        
    }
    
    

    
}
